Bubble Sort is a simple sorting algorithm that repeatedly steps through the list of elements, compares adjacent elements, and swaps them if they are in the wrong order. The pass through the list is repeated until the entire list becomes sorted. It is called "Bubble Sort" because smaller elements "bubble" to the top of the list with each pass.
#include <stdio.h>
void bubbleSort(int arr[], int size) {
int temp;
for (int i = 0; i < size - 1; i++) {
for (int j = 0; j < size - i - 1; j++) {
// Compare adjacent elements and swap if necessary
if (arr[j] > arr[j + 1]) {
temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;
}
}
}
}
int main() {
int arr[] = {64, 34, 25, 12, 22, 11, 90};
int size = sizeof(arr) / sizeof(arr[0]);
printf("Original Array: ");
for (int i = 0; i < size; i++) {
printf("%d ", arr[i]);
}
printf("\n");
// Sort the array using Bubble Sort
bubbleSort(arr, size);
printf("Sorted Array: ");
for (int i = 0; i < size; i++) {
printf("%d ", arr[i]);
}
printf("\n");
return 0;
}
Original Array: 64 34 25 12 22 11 90
Sorted Array: 11 12 22 25 34 64 90
What is Bubble Sort?
How does Bubble Sort work?
What is the time complexity of Bubble Sort in the worst case?
What is the main drawback of Bubble Sort?
What type of sorting algorithm is Bubble Sort?